package validator

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTrans "github.com/go-playground/validator/v10/translations/en"
	zhTrans "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

var Trans ut.Translator

func InitTrans(locale string) (err error) {

	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {

		// 注册获取 json tag 的自定义方法
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			return strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
		})
		zhT := zh.New()
		enT := en.New()
		uni := ut.New(enT, zhT, enT)

		var ok bool
		Trans, ok = uni.GetTranslator(locale)

		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s) failed", locale)
		}

		switch locale {
		case "en":
			err = enTrans.RegisterDefaultTranslations(v, Trans)
		case "zh":
			err = zhTrans.RegisterDefaultTranslations(v, Trans)
		default:
			err = enTrans.RegisterDefaultTranslations(v, Trans)
		}
	}

	return
}

// 去除提示信息中的结构体名称
func RemoveTopStruct(fields map[string]string) map[string]string {

	res := make(map[string]string, len(fields))
	for k, v := range fields {
		nk := k[strings.Index(k, ".")+1:]
		res[nk] = v
	}
	return res
}
